"use strict";
;(function ($) {
    $.fn.scollLoading = function (options) {
        if (methods[options]) {
            // 如果存在该方法就调用该方法
            return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof options === 'object' || !options) {
            // 如果传进来的参数是"{...}", 就认为是初始化操作.
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + options + ' does not exist on jQuery.mmClock');
        }
    },
        $.fn.scollLoading.defaults = {
            api: 'https://api.douban.com/v2/event/list',
            params: {
                start: 5,
                type: 'music',
                count: 10,
                loc: 'beijing'
            }
        }
    // $.fn.scollLoading.defaults = {
    //     url: '',
    //     layer: null, // 当前等级
    //     page: 1,// 当前页
    //     rows: 4,// 每页数据
    //     total: 0,
    //     name: null,//搜索名称
    //     sort: null,//排序
    //     rank: null,//级别
    //     maxPage: 0,// 最大页数
    //     nowIndex: 0,// 当前光标所指的下标
    //     datas: [],// 数据
    //     param: {}
    // }
    // var $main = $('#wrapper');
    // var $list = $main.find('#events-list');
    // var $pullDown = $main.find('#pull-down');
    // var $pullDownLabel = $main.find('#pull-down-label');
    // var $pullUp = $main.find('#pull-up');
    // var topOffset = -$pullDown.outerHeight();

    var _private = {
        getURL: function (options) {
            var queries = ['callback=?'];
            for (var key in  options.params) {
                if (key !== 'start') {
                    queries.push(key + '=' + options.params[key]);
                }
            }
            queries.push('start=');
            return options.api + '?' + queries.join('&');
        },
        initUrl: function (options, page) {
            page = page == null ? options.page : page;
            var url = null;
            if (options.layer != null) {
                url = options.url + options.layer + '/' + page + "/" + options.rows;
            } else {
                url = options.url + page + "/" + options.rows;
            }
            for (var i in options.param) {
                if (options.param[i] != null) {
                    url += '/' + options.param[i]
                }
            }
            return url;
        },
        renderList: function (options, start, type) {
            //console.log(event)
            //var _this = this;
            var $el = options.$pullDown;
            if (type === 'load') {
                $el = options.$pullUp;
            }
            // console.log(options.URL);
            var url = _private.getURL(options);
            $.getJSON(url + start).then(function (data) {
                console.log(data);
                options.self.total = data.total;
                var html = options.self.compiler(data.events);
                // options.datas = data;
                // options.type = type;
                // options.render(options);
                if (type === 'refresh') {
                    options.$list.children('li').first().before(html);
                } else if (type === 'load') {
                    options.$list.append(html);

                } else {
                    options.$list.html(html);
                }

                // refresh iScroll
                setTimeout(function () {
                    options.self.iScroll.refresh();
                }, 100);
            }, function () {
                console.log('Error...')
            }).always(function () {
                _private.resetLoading($el);
                if (type !== 'load') {
                    options.self.iScroll.scrollTo(0, options.topOffset, 800, $.AMUI.iScroll.utils.circular);
                }
            });

        },

        setLoading: function ($el) {
            $el.addClass('loading');
        },

        resetLoading: function ($el) {
            $el.removeClass('loading');
        },

        handlePullDown: function (options) {
            console.log('handle pull down' + options.self.prev);
            if (options.self.prev > 0) {
                _private.setLoading( options.$pullDown);
                //这里修改页码
                options.self.prev -= options.rows;
                _private.renderList(options, options.self.prev, 'refresh');
            } else {
                console.log('别刷了，没有了');
            }
        },

        handlePullUp: function (options) {
            console.log('handle pull up' + options.self.next);
            if (options.self.next < options.self.total) {
                _private.setLoading( options.$pullUp);
                //这里修改页码
                options.self.next += options.rows;
                _private.renderList(options, options.self.next, 'load');
            } else {
                console.log(options.self.next);
                // this.iScroll.scrollTo(0, topOffset);
            }
        },
        generLoadDom: function () {
            var loadDom = {
                pullDown: '<div class="pull-action loading" id="pull-down"><span class="am-icon-arrow-down pull-label"id="pull-down-label"> 下拉刷新</span><span class="am-icon-spinner am-icon-spin"></span></div>',
                pullUp: '<div class="pull-action" id="pull-up"><span class="am-icon-arrow-down pull-label" id="pull-up-label"> 上拉加载更多</span><span class="am-icon-spinner am-icon-spin"></span></div>'
            };
            return loadDom;
        }
    }

    var methods = {
        renderEvent: function (render) {
            render.apply(this, {});
        },
        init: function (option) {
            //var _this = this;
            this.find('.events-list').before(_private.generLoadDom().pullDown);
            this.find('.events-list').after(_private.generLoadDom().pullUp);

            var pullFormTop = false;
            var pullStart;
            var options = $.extend({}, $.fn.scollLoading.defaults, option);
            options.$list = this.find('.events-list');
            options.$pullDown = this.find('#pull-down');
            options.$pullDownLabel = this.find('#pull-down-label');
            options.$pullUp = this.find('#pull-up');
            options.topOffset = -options.$pullDown.outerHeight();

            this.compiler = Handlebars.compile($('#tpi-list-item').html());
            this.prev = this.next = this.start = options.page;
            this.total = null;
            options.self = this;

            var myScroll = this.iScroll = new $.AMUI.iScroll(this[0], {
                preventDefault: false,//（把这句加上去哦）
                preventDefaultException: {tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|A)$/},

            });


            //

            // // myScroll.scrollTo(0, topOffset);
            //options.URL = _private.getURL(options);


            _private.renderList(options, options.page);

            myScroll.on('scrollStart', function () {
                if (this.y >= options.topOffset) {
                    pullFormTop = true;
                }
                console.log(this.y+" "+this.directionY);

                pullStart = this.y;
                // console.log(this);
            });

            myScroll.on('scrollEnd', function () {
                if (pullFormTop && this.directionY === -1) {
                    _private.handlePullDown(options);
                }
                pullFormTop = false;

                // pull up to load more
                if (pullStart === this.y && (this.directionY === 1)) {
                    _private.handlePullUp(options);
                }
            });
        }
    }


    /*    $(function () {
     var app = new EventsList(null, {
     api: 'https://api.douban.com/v2/event/list',
     params: {
     start: 100,
     type: 'music',
     count: 10,
     loc: 'beijing'
     }
     });
     });*/

})(window.jQuery);
